package jnpf.controller;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jnpf.base.ActionResult;
import jnpf.base.UserInfo;
import jnpf.model.ragFlow.common.DocumentIdsReq;
import jnpf.model.ragFlow.common.IdReq;
import jnpf.model.ragFlow.common.RagFlowApiResult;
import jnpf.model.ragFlow.file.DocInfo;
import jnpf.model.ragFlow.file.DocumentListRequest;
import jnpf.model.ragFlow.file.FileListResp;
import jnpf.model.themefile.HandleResp;
import jnpf.model.themefile.RelationData;
import jnpf.model.themefile.ThemeBound;
import jnpf.model.themefile.ThemeFileInitResp;
import jnpf.service.*;
import jnpf.entity.*;
import jnpf.util.*;
import jnpf.model.knowfilemange.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.*;

import jnpf.base.vo.PageListVO;
import jnpf.base.vo.PaginationVO;
import jnpf.base.vo.DownloadVO;
import jnpf.config.ConfigValueUtil;

import java.io.IOException;
import java.util.stream.Collectors;

import org.springframework.web.multipart.MultipartFile;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;

import cn.xuyanwu.spring.file.storage.FileInfo;
import lombok.Cleanup;
import jnpf.model.visualJson.config.HeaderModel;
import jnpf.base.model.ColumnDataModel;
import jnpf.base.util.VisualUtils;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

/**
 * knowFileMange
 *
 * @版本： V3.5
 * @版权： 引迈信息技术有限公司（https://www.jnpfsoft.com）
 * @作者： JNPF开发平台组
 * @日期： 2025-05-19
 */
@Slf4j
@RestController
@Tag(name = "knowFileMange", description = "example")
@RequestMapping("/api/example/KnowFileMange")
public class KnowFileMangeController {

    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;

    @Autowired
    private UserProvider userProvider;

    @Autowired
    private KnowFileMangeService knowFileMangeService;

    @Autowired
    private KnowFileMetadataService knowFileMetadataService;


    @Autowired
    private ConfigValueUtil configValueUtil;

    @Autowired
    private RagFlowFileService ragFlowFileService;

    @Autowired
    private RagChunksService ragChunksService;
    @Autowired
    private FileMangeService fileMangeService;

    @Autowired
    private ThemeFileService themeFileService;
    @Autowired
    private ThemeService themeService;
    @Autowired
    private KnowMangeService knowMangeService;
    @Autowired
    private ThemeTreeService themeTreeService;


    /**
     * 列表
     *
     * @param knowFileMangePagination
     * @return
     */
    @Operation(summary = "获取列表")
    @PostMapping("/getList")
    public ActionResult list(@RequestBody KnowFileMangePagination knowFileMangePagination) throws IOException {
        // 构建查询条件
        QueryWrapper<KnowFileMangeEntity> queryWrapper = new QueryWrapper<>();


        // 根据知识库名称查询
        QueryWrapper<KnowMangeEntity> knowMangeEntityQueryWrapper = new QueryWrapper<>();
        knowMangeEntityQueryWrapper.lambda().like(KnowMangeEntity::getName, knowFileMangePagination.getKnowledgeBaseName());
        List<KnowMangeEntity> knowMangeList = knowMangeService.list(knowMangeEntityQueryWrapper);

        // 如果查询到知识库ID列表，则添加到查询条件中
        if (!knowMangeList.isEmpty()) {
            List<String> knowIds = knowMangeList.stream()
                    .map(KnowMangeEntity::getId)
                    .collect(Collectors.toList());
            String[] knowIdArray = knowIds.toArray(new String[knowIds.size()]);
            queryWrapper.lambda().in(KnowFileMangeEntity::getKnowid, knowIdArray);
        } else {
            // 如果没有查询到知识库ID，则返回空结果
            PageListVO pageListVO = new PageListVO();
            pageListVO.setList(new ArrayList<>());
            PaginationVO paginationVO = new PaginationVO();
            paginationVO.setCurrentPage(knowFileMangePagination.getCurrentPage());
            paginationVO.setPageSize(knowFileMangePagination.getPageSize());
            paginationVO.setTotal(Math.toIntExact(knowFileMangePagination.getTotal()));
            pageListVO.setPagination(paginationVO);
            return ActionResult.success(pageListVO);
        }


        // 根据文件名称查询
        if (StringUtil.isNotEmpty(knowFileMangePagination.getFileName())) {
            queryWrapper.lambda().like(KnowFileMangeEntity::getName, knowFileMangePagination.getFileName());
        }

        // 根据是否启用查询
        if (StringUtil.isNotEmpty(knowFileMangePagination.getIsEnabled())) {
            queryWrapper.lambda().eq(KnowFileMangeEntity::getStatus, knowFileMangePagination.getIsEnabled());
        }

        // 执行分页查询
        Page<KnowFileMangeEntity> page = new Page<>(knowFileMangePagination.getCurrentPage(), knowFileMangePagination.getPageSize());
        IPage<KnowFileMangeEntity> iPage = knowFileMangeService.page(page, queryWrapper);

        // 在处理查询结果前，先获取所有知识库ID
        List<String> knowIds = iPage.getRecords().stream()
                .map(KnowFileMangeEntity::getKnowid)
                .collect(Collectors.toList());

        List<Map<String, Object>> realList = new ArrayList<>();
        if(!knowIds.isEmpty()){
            // 批量查询知识库名称映射
            Map<String, String> knowledgeBaseNameMap = knowMangeService.getByIds(knowIds).stream()
                    .collect(Collectors.toMap(KnowMangeEntity::getId, KnowMangeEntity::getName));

            // 处理查询结果
            for (KnowFileMangeEntity entity : iPage.getRecords()) {
                Map<String, Object> knowFileMangeMap = JsonUtil.entityToMap(entity);
                knowFileMangeMap.put("id", knowFileMangeMap.get("id"));
                // 从映射中获取知识库名称
                String knowledgeBaseName = knowledgeBaseNameMap.get(entity.getKnowid());
                knowFileMangeMap.put("knowledgeBaseName", knowledgeBaseName != null ? knowledgeBaseName : "");
                realList.add(knowFileMangeMap);
            }
        }

        // 获取解析中的数据，从rag中获取解析状态
        List<Map<String, Object>> processingList = new ArrayList<>();
        for (Map<String, Object> entity : realList) {
            String handle = entity.get("handle").toString();
            if (StringUtil.isNotEmpty(handle) && (handle.equals("1"))) {
                processingList.add(entity);
            }
        }

        ArrayList<HandleResp> handleOk=new ArrayList<>();

        for (Map<String, Object> entity : processingList) {
            String datasetId = (String) entity.get("datasetid");
            String ragfileid = (String) entity.get("ragfileid");
            DocumentListRequest documentListRequest = new DocumentListRequest();
            documentListRequest.setId(ragfileid);
            RagFlowApiResult<FileListResp> ragFlowApiResult = null;
            try {
                ragFlowApiResult = ragFlowFileService.listDocuments(datasetId, documentListRequest);
            } catch (Exception e) {
                log.error(e.getMessage());
            }
            if (ragFlowApiResult.getCode() == 0) {
                FileListResp data = ragFlowApiResult.getData();
                List<DocInfo> docs = data.getDocs();
                for (DocInfo doc : docs) {
                    if(doc.getId().equals(ragfileid)){
                        String run = doc.getRun();
                        Double progress = doc.getProgress();

                        if("DONE".equals(run) && progress == 1.0){
                            // 解析完成
                            HandleResp handleResp = new HandleResp();
                            handleResp.setId(entity.get("id").toString());
                            handleResp.setChunkCount(doc.getChunk_count());
                            handleResp.setStatus("2");
                            handleOk.add(handleResp);
                            entity.put("blocks",doc.getChunk_count());
                            entity.put("handle","2");
                        } else if("FAIL".equals(run)){
                            // 解析失败
                            entity.put("handle","3");
                            HandleResp handleResp = new HandleResp();
                            handleResp.setId(entity.get("id").toString());
                            handleResp.setStatus("3");
                            handleOk.add(handleResp);
                        } else if("RUNNING".equals(run)){
                            // 解析中
                            entity.put("handle","1");
                            entity.put("progress", progress);
                        } else {
                            // 其他情况保持原状态
                            entity.put("handle","0");
                        }
                    }
                }
            }else{
                entity.put("handle","3");
                HandleResp handleResp = new HandleResp();
                handleResp.setId(entity.get("id").toString());
                handleResp.setStatus("3");
                handleOk.add(handleResp);
            }
        }

        //解析完毕的设置handle为2
        fileMangeService.updateHandleByIds(handleOk);

        // 返回分页结果
        PageListVO vo = new PageListVO();
        vo.setList(realList);
        PaginationVO paginationVO = new PaginationVO();
        paginationVO.setCurrentPage(iPage.getCurrent());
        paginationVO.setPageSize(iPage.getSize());
        paginationVO.setTotal(Math.toIntExact(iPage.getTotal()));
        vo.setPagination(paginationVO);
        return ActionResult.success(vo);
    }



    /**
     * 创建
     *
     * @param knowFileMangeForm
     * @return
     */
    @PostMapping()
    @Operation(summary = "创建")
    public ActionResult create(@RequestBody @Valid KnowFileMangeForm knowFileMangeForm) {
        String b = knowFileMangeService.checkForm(knowFileMangeForm, 0);
        if (StringUtil.isNotEmpty(b)) {
            return ActionResult.fail(b);
        }
        try {
            knowFileMangeService.saveOrUpdate(knowFileMangeForm, null, true);
        } catch (Exception e) {
            return ActionResult.fail("新增数据失败");
        }
        return ActionResult.success("创建成功");
    }

    /**
     * 导出Excel
     *
     * @return
     */
    @Operation(summary = "导出Excel")
    @PostMapping("/Actions/Export")
    public ActionResult Export(@RequestBody KnowFileMangePagination knowFileMangePagination) throws IOException {
        if (StringUtil.isEmpty(knowFileMangePagination.getSelectKey())) {
            return ActionResult.fail("请选择导出字段");
        }
        List<KnowFileMangeEntity> list = knowFileMangeService.getList(knowFileMangePagination);
        List<Map<String, Object>> realList = new ArrayList<>();
        for (KnowFileMangeEntity entity : list) {
            Map<String, Object> knowFileMangeMap = JsonUtil.entityToMap(entity);
            knowFileMangeMap.put("id", knowFileMangeMap.get("id"));
            //副表数据
            //子表数据
            List<KnowFileMetadataEntity> knowFileMetadataList = knowFileMangeService.getKnowFileMetadataList(entity.getId(), knowFileMangePagination);
            knowFileMangeMap.put("tableField107", JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(knowFileMetadataList)));
            realList.add(knowFileMangeMap);
        }
        //数据转换
        realList = generaterSwapUtil.swapDataList(realList, KnowFileMangeConstant.getFormData(), KnowFileMangeConstant.getColumnData(), knowFileMangePagination.getModuleId(), false);
        String[] keys = !StringUtil.isEmpty(knowFileMangePagination.getSelectKey()) ? knowFileMangePagination.getSelectKey() : new String[0];
        UserInfo userInfo = userProvider.get();
        DownloadVO vo = this.creatModelExcel(configValueUtil.getTemporaryFilePath(), realList, keys, userInfo);
        return ActionResult.success(vo);
    }

    /**
     * 导出表格方法
     */
    public DownloadVO creatModelExcel(String path, List<Map<String, Object>> list, String[] keys, UserInfo userInfo) {
        DownloadVO vo = DownloadVO.builder().build();
        List<ExcelExportEntity> entitys = new ArrayList<>();
        if (keys.length > 0) {
            ExcelExportEntity tableField107ExcelEntity = new ExcelExportEntity("设计子表", "tableField107");
            List<ExcelExportEntity> tableField107List = new ArrayList<>();
            for (String key : keys) {
                switch (key) {
                    case "knowid":
                        entitys.add(new ExcelExportEntity("知识库名称", "knowid"));
                        break;
                    case "name":
                        entitys.add(new ExcelExportEntity("名称", "name"));
                        break;
                    case "blocks":
                        entitys.add(new ExcelExportEntity("分块数", "blocks"));
                        break;
                    case "uptime":
                        entitys.add(new ExcelExportEntity("上传日期", "uptime"));
                        break;
                    case "type":
                        entitys.add(new ExcelExportEntity("切片方法", "type"));
                        break;
                    case "status":
                        entitys.add(new ExcelExportEntity("启用", "status"));
                        break;
                    case "handle":
                        entitys.add(new ExcelExportEntity("解析状态", "handle"));
                        break;
                    case "datasetid":
                        entitys.add(new ExcelExportEntity("rag数据集id", "datasetid"));
                        break;
                    case "ragfileid":
                        entitys.add(new ExcelExportEntity("rag文件id", "ragfileid"));
                        break;
                    case "tableField107-type":
                        tableField107List.add(new ExcelExportEntity("文本类型", "type"));
                        break;
                    case "tableField107-name":
                        tableField107List.add(new ExcelExportEntity("文本名称", "name"));
                        break;
                    case "tableField107-uptype":
                        tableField107List.add(new ExcelExportEntity("上传类型", "uptype"));
                        break;
                    case "tableField107-datasetid":
                        tableField107List.add(new ExcelExportEntity("rag数据集id", "datasetid"));
                        break;
                    case "tableField107-ragfileid":
                        tableField107List.add(new ExcelExportEntity("rag文件id", "ragfileid"));
                        break;
                    case "tableField107-ragdataid":
                        tableField107List.add(new ExcelExportEntity("rag数据块id", "ragdataid"));
                        break;
                    default:
                        break;
                }
            }
            if (tableField107List.size() > 0) {
                tableField107ExcelEntity.setList(tableField107List);
                entitys.add(tableField107ExcelEntity);
            }
        }

        ExportParams exportParams = new ExportParams(null, "表单信息");
        exportParams.setType(ExcelType.XSSF);
        try {
            @Cleanup Workbook workbook = new HSSFWorkbook();
            if (entitys.size() > 0) {
                if (list.size() == 0) {
                    list.add(new HashMap<>());
                }
                //去除空数据
                List<Map<String, Object>> dataList = new ArrayList<>();
                for (Map<String, Object> map : list) {
                    int i = 0;
                    for (String key : keys) {
                        //子表
                        if (key.toLowerCase().startsWith("tablefield")) {
                            String tableField = key.substring(0, key.indexOf("-"));
                            String field = key.substring(key.indexOf("-") + 1);
                            Object o = map.get(tableField);
                            if (o != null) {
                                List<Map<String, Object>> childList = (List<Map<String, Object>>) o;
                                for (Map<String, Object> childMap : childList) {
                                    if (childMap.get(field) != null) {
                                        i++;
                                    }
                                }
                            }
                        } else {
                            Object o = map.get(key);
                            if (o != null) {
                                i++;
                            }
                        }
                    }
                    if (i > 0) {
                        dataList.add(map);
                    }
                }
                //复杂表头-表头和数据处理
                ColumnDataModel columnDataModel = JsonUtil.getJsonToBean(KnowFileMangeConstant.getColumnData(), ColumnDataModel.class);
                List<HeaderModel> complexHeaderList = columnDataModel.getComplexHeaderList();
                if (!Objects.equals(columnDataModel.getType(), 3) && !Objects.equals(columnDataModel.getType(), 5)) {
                    entitys = VisualUtils.complexHeaderHandel(entitys, complexHeaderList);
                    dataList = VisualUtils.complexHeaderDataHandel(dataList, complexHeaderList);
                }

                workbook = ExcelExportUtil.exportExcel(exportParams, entitys, dataList);
            }
            String fileName = "表单信息" + DateUtil.dateNow("yyyyMMdd") + "_" + RandomUtil.uuId() + ".xlsx";
            MultipartFile multipartFile = ExcelUtil.workbookToCommonsMultipartFile(workbook, fileName);
            String temporaryFilePath = configValueUtil.getTemporaryFilePath();
            FileInfo fileInfo = FileUploadUtils.uploadFile(multipartFile, temporaryFilePath, fileName);
            vo.setName(fileInfo.getFilename());
            vo.setUrl(UploaderUtil.uploaderFile(fileInfo.getFilename() + "#" + "Temporary") + "&name=" + fileName);
        } catch (Exception e) {
            log.error("信息导出Excel错误:{}", e.getMessage());
            e.printStackTrace();
        }
        return vo;
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @DeleteMapping("/batchRemove")
    @Transactional
    @Operation(summary = "批量删除")
    public ActionResult batchRemove(@RequestBody String ids) {
        List<String> idList = JsonUtil.getJsonToList(ids, String.class);
        int i = 0;
        for (String allId : idList) {
            this.delete(allId);
            i++;
        }
        if (i == 0) {
            return ActionResult.fail("删除失败");
        }
        return ActionResult.success("删除成功");
    }

    /**
     * 编辑
     *
     * @param id
     * @param knowFileMangeForm
     * @return
     */
    @PutMapping("/{id}")
    @Operation(summary = "更新")
    public ActionResult update(@PathVariable("id") String id, @RequestBody @Valid KnowFileMangeForm knowFileMangeForm, @RequestParam(value = "isImport", required = false) boolean isImport) {
        knowFileMangeForm.setId(id);
        if (!isImport) {
            String b = knowFileMangeService.checkForm(knowFileMangeForm, 1);
            if (StringUtil.isNotEmpty(b)) {
                return ActionResult.fail(b);
            }
        }
        KnowFileMangeEntity entity = knowFileMangeService.getInfo(id);
        if (entity != null) {
            try {
                knowFileMangeService.saveOrUpdate(knowFileMangeForm, id, false);
            } catch (Exception e) {
                return ActionResult.fail("修改数据失败");
            }
            return ActionResult.success("更新成功");
        } else {
            return ActionResult.fail("更新失败，数据不存在");
        }
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @Operation(summary = "删除")
    @DeleteMapping("/{id}")
    @Transactional
    public ActionResult delete(@PathVariable("id") String id) {
        KnowFileMangeEntity entity = knowFileMangeService.getInfo(id);
        if (entity != null) {

            //主表数据删除
            knowFileMangeService.delete(entity);
            QueryWrapper<KnowFileMetadataEntity> queryWrapperKnowFileMetadata = new QueryWrapper<>();
            queryWrapperKnowFileMetadata.lambda().eq(KnowFileMetadataEntity::getFileid, entity.getId());

            //子表数据删除
            knowFileMetadataService.remove(queryWrapperKnowFileMetadata);

            //主题关联文件删除
            QueryWrapper<ThemeFileEntity> themeFileEntityQueryWrapper = new QueryWrapper<>();
            themeFileEntityQueryWrapper.lambda().eq(ThemeFileEntity::getFileid, entity.getId());
            themeFileService.remove(themeFileEntityQueryWrapper);

            //文件元数据删除
            QueryWrapper<KnowFileMetadataEntity> knowFileMetadataEntityQueryWrapper = new QueryWrapper<>();
            knowFileMetadataEntityQueryWrapper.lambda().eq(KnowFileMetadataEntity::getFileid, entity.getId());
            knowFileMetadataService.remove(knowFileMetadataEntityQueryWrapper);

            //设置文件数量
            knowMangeService.getSetAmount( entity.getKnowid());

            String datasetid = entity.getDatasetid();
            if (StringUtil.isNotEmpty(datasetid)) {
                try {
                    // 删除 RAG 对应文件
                    ragFlowFileService.deleteDocuments(datasetid, new IdReq(entity.getRagfileid()));

                    // 获取 RAG 数据块列表
//                    QueryWrapper<KnowFileMetadataEntity> queryWrapper = new QueryWrapper<>();
//                    queryWrapper.lambda().eq(KnowFileMetadataEntity::getFileid, entity.getId());
//                    List<KnowFileMetadataEntity> metadataList = knowFileMetadataService.list(queryWrapper);

                    //没有这个api了，改为url直接请求
//                    // 删除 RAG 数据块
//                    for (KnowFileMetadataEntity metadata : metadataList) {
//                        if (StringUtil.isNotEmpty(metadata.getRagdataid())) {
//                            DeleteChunksRequest deleteRequest = new DeleteChunksRequest();
//                            deleteRequest.setChunk_ids(Collections.singletonList(metadata.getRagdataid()));
//                            ragChunksService.deleteChunks(datasetid, metadata.getRagfileid(), deleteRequest);
//                        }
//                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }
            }


        }
        return ActionResult.success("删除成功");
    }

    /**
     * 表单信息(详情页)
     * 详情页面使用-转换数据
     *
     * @param id
     * @return
     */
    @Operation(summary = "表单信息(详情页)")
    @GetMapping("/detail/{id}")
    public ActionResult detailInfo(@PathVariable("id") String id) {
        KnowFileMangeEntity entity = knowFileMangeService.getInfo(id);
        if (entity == null) {
            return ActionResult.fail("表单数据不存在！");
        }
        Map<String, Object> knowFileMangeMap = JsonUtil.entityToMap(entity);
        knowFileMangeMap.put("id", knowFileMangeMap.get("id"));
        //副表数据
        //子表数据
        List<KnowFileMetadataEntity> knowFileMetadataList = knowFileMangeService.getKnowFileMetadataList(entity.getId());
        knowFileMangeMap.put("tableField107", JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(knowFileMetadataList)));
        knowFileMangeMap = generaterSwapUtil.swapDataDetail(knowFileMangeMap, KnowFileMangeConstant.getFormData(), "691941117691713989", false);
        return ActionResult.success(knowFileMangeMap);
    }

    /**
     * 获取详情(编辑页)
     * 编辑页面使用-不转换数据
     *
     * @param id
     * @return
     */
    @Operation(summary = "信息")
    @GetMapping("/{id}")
    public ActionResult info(@PathVariable("id") String id) {
        KnowFileMangeEntity entity = knowFileMangeService.getInfo(id);
        if (entity == null) {
            return ActionResult.fail("表单数据不存在！");
        }
        Map<String, Object> knowFileMangeMap = JsonUtil.entityToMap(entity);
        knowFileMangeMap.put("id", knowFileMangeMap.get("id"));
        //副表数据
        //子表数据
        List<KnowFileMetadataEntity> knowFileMetadataList = knowFileMangeService.getKnowFileMetadataList(entity.getId());
        knowFileMangeMap.put("knowFileMetadataList", JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(knowFileMetadataList)));
        knowFileMangeMap = generaterSwapUtil.swapDataForm(knowFileMangeMap, KnowFileMangeConstant.getFormData(), KnowFileMangeConstant.TABLEFIELDKEY, KnowFileMangeConstant.TABLERENAMES);
        return ActionResult.success(knowFileMangeMap);
    }

    /**
     * 解析文件
     *
     * @param id
     * @return
     */
    @Operation(summary = "解析文件")
    @GetMapping("/analysis/{id}")
    public ActionResult analysis(@PathVariable("id") String id) {
        KnowFileMangeEntity entity = knowFileMangeService.getInfo(id);
        if (entity == null) {
            return ActionResult.fail("表单数据不存在！");
        }

        return knowFileMangeService.analysisFile(entity);
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @PostMapping("/batch/{type}")
    @Transactional
    @Operation(summary = "批量操作")
    public ActionResult batchHandle(@RequestBody List<String> ids, @PathVariable("type") String type) {
        if (ids.isEmpty()) {
            return ActionResult.fail("未提供有效ID");
        }
        try {
            switch (type) {
                case "1":
                    batchUpdateStatus(ids, "1");
                    break;
                case "2":
                    batchUpdateStatus(ids, "0");
                    break;
                case "3":
                    batchParseFailedDocuments(ids );
                    break;
                case "4":
                    batchParseDocuments(ids, false);
                    break;
                default:
                    return ActionResult.fail("不支持的操作类型");
            }
            return ActionResult.success("操作成功");
        } catch (Exception e) {
            return ActionResult.fail("操作失败: " + e.getMessage());
        }
    }




    @PostMapping("/upFile/{fileId}")
    @Transactional
    @Operation(summary = "上传主题和文件绑定信息")
    public ActionResult batchRemove(@RequestBody List<ThemeBound> themeFileUpReq, @PathVariable("fileId") String fileId) {
        try {
            themeFileService.bindThemeToFile(themeFileUpReq, fileId);
            return ActionResult.success("操作成功");
        } catch (Exception e) {
            return ActionResult.fail("操作失败: " + e.getMessage());
        }
    }

    @PostMapping("/getThemeFile/{fileId}")
    @Transactional
    @Operation(summary = "获取文件绑定的主题")
    public ActionResult getThemeFile(@PathVariable("fileId") String fileId) {
        try {
            List<String> themeIds = themeFileService.getThemesByFileId(fileId);
            return ActionResult.success(themeIds);
        } catch (Exception e) {
            return ActionResult.fail("操作失败: " + e.getMessage());
        }
    }

    /**
     * 获取子表数据
     *
     * @param mainId 主表记录的 ID
     * @return 子表数据列表
     */
    @Operation(summary = "获取子表数据")
    @GetMapping("/metadata/{mainId}")
    public ActionResult<List<KnowFileMetadataEntity>> getKnowFileMetadataList(@PathVariable String mainId) {
        List<KnowFileMetadataEntity> metadataList = knowFileMetadataService.getKnowFileMetadataList(mainId);
        return ActionResult.success(metadataList);
    }

    /**
     * 更新子表数据
     *
     * @param metadataList 子表数据列表
     * @return 操作结果
     */
    @Operation(summary = "更新子表数据")
    @PutMapping("/metadata")
    public ActionResult<String> updateKnowFileMetadataList(@RequestBody List<KnowFileMetadataEntity> metadataList) {
        return knowFileMetadataService.updateKnowFileMetadataList(metadataList);
    }


    /**
     * 同一级主题下的实体,上一级主题的实体,下一级主题的实体
     *
     * @return 操作结果
     */
    @Operation(summary = "获取主题关联实体")
    @GetMapping("/getObjByOneTheme/{themeFileId}")
    public ActionResult<RelationData> getObjByOneTheme(@PathVariable("themeFileId") String themeFileId) throws Exception {
        ThemeFileEntity byId = themeFileService.getById(themeFileId);
        String themeid = byId.getThemeid();
        String nodeid = byId.getNodeid();
        RelationData relationData =themeTreeService.getTreeByThemeIdAndNodeId(themeid, nodeid);
        return ActionResult.success(relationData);
    }
    /**
     * 获取文件页面初始化数据
     *
     * @return 操作结果
     */
    @Operation(summary = "获取文件页面初始化数据")
    @GetMapping("/fileInitData/{fileId}")
    public ActionResult<ThemeFileInitResp> fileInitData(@PathVariable String fileId) {
        ThemeFileInitResp themeFileInitResp = new ThemeFileInitResp();

        // 初始化数据

        //下拉主版本主题数据
        QueryWrapper<ThemeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ISMAIN", 1);
        queryWrapper.select("ID", "THEMENAME", "THEMETYPE", "VERSION", "FIRSTVERSION");
        List<ThemeEntity> themeEntities = themeService.list(queryWrapper);
        themeFileInitResp.setThemeDataList(themeEntities);


        //文件选中的主题数据
        QueryWrapper<ThemeFileEntity> queryWrapperThemeFile = new QueryWrapper<>();
        queryWrapperThemeFile.eq("FILEID", fileId);
        if (!themeEntities.isEmpty()) {
            queryWrapperThemeFile.in("THEMEID", themeEntities.stream().map(ThemeEntity::getId).collect(Collectors.toList()));
        }
        List<ThemeFileEntity> themeFileEntities = themeFileService.list(queryWrapperThemeFile);
        List<String> themeIds = themeFileEntities.stream().map(ThemeFileEntity::getThemeid).collect(Collectors.toList());
        themeFileInitResp.setSelectThemeList(themeIds);

        //从queryWrapperThemeFile中提取出ThemeBound列表
        List<ThemeBound> themeBoundList = themeFileEntities.stream().map(themeFileEntity -> {
            ThemeBound themeBound = new ThemeBound();
            themeBound.setFileid(themeFileEntity.getId());
            themeBound.setNodeid(themeFileEntity.getNodeid());
            themeBound.setThemeid(themeFileEntity.getThemeid());
            themeBound.setType("0");
            return themeBound;
        }).collect(Collectors.toList());

        themeFileInitResp.setThemeBoundList(themeBoundList);

//        List<TreeVO> allTreeNodes = new ArrayList<>();
//
//        for (String themeId : themeIds) {
//            List<TreeVO> themeTree = themeService.getThemeTree(themeId, "1");
//            allTreeNodes.addAll(themeTree);
//        }
//        Tree tree=new Tree("0","主题层级列表");
//        tree.setChildren(allTreeNodes);
//
//        themeFileInitResp.setTree(tree);

        return ActionResult.success(themeFileInitResp);

    }

    public String getKnowIdByName(String knowledgeBaseName) {
        // 根据知识库名称查询对应的ID
        QueryWrapper<KnowMangeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(KnowMangeEntity::getName, knowledgeBaseName);
        KnowMangeEntity knowMangeEntity = knowMangeService.getOne(queryWrapper);
        if (knowMangeEntity != null) {
            return knowMangeEntity.getId();
        }
        return null;
    }


    // 批量更新状态方法
    private void batchUpdateStatus(List<String> idList, String status) {
        for (String id : idList) {
            FileMangeEntity fileMangeEntity = fileMangeService.getById(id);
            if (fileMangeEntity != null) {
                fileMangeEntity.setStatus(status);
                fileMangeService.updateById(fileMangeEntity);
            }
        }
    }
    //批量处理解析中和解析失败的情况
    private void batchParseFailedDocuments(List<String> idList) throws Exception {
        List<String> validIds = new ArrayList<>();
        String datasetId = null;

        for (String id : idList) {
            FileMangeEntity fileMangeEntity = fileMangeService.getById(id);
            if (fileMangeEntity != null) {
                if (datasetId == null) {
                    datasetId = fileMangeEntity.getDatasetid();
                }
                // 同时处理未解析(0)和解析失败(3)的文档
                if ("0".equals(fileMangeEntity.getHandle()) || "3".equals(fileMangeEntity.getHandle())) {
                    validIds.add(fileMangeEntity.getRagfileid());
                }
            }
        }

        if (!validIds.isEmpty() && datasetId != null) {
            DocumentIdsReq documentIdsReq = new DocumentIdsReq();
            documentIdsReq.setDocument_ids(validIds);

            RagFlowApiResult ragFlowApiResult = ragFlowFileService.parseDocuments(datasetId, documentIdsReq);
            if (ragFlowApiResult.getCode() == 0) {
                for (String id : idList) {
                    FileMangeEntity fileMangeEntity = fileMangeService.getById(id);
                    if (fileMangeEntity != null &&
                            ("0".equals(fileMangeEntity.getHandle()) || "3".equals(fileMangeEntity.getHandle()))) {
                        fileMangeEntity.setHandle("1"); // 设置为解析中状态
                        fileMangeService.updateById(fileMangeEntity);
                    }
                }
            } else {
                throw new Exception(ragFlowApiResult.getMessage());
            }
        }
    }

    private void batchParseDocuments(List<String> idList, boolean isParse) throws Exception {
        // 步骤 1: 初始化变量
        List<String> validIds = new ArrayList<>();
        String datasetId = null;

        // 步骤 2: 筛选有效文件 ID 并确定数据集 ID
        for (String id : idList) {
            FileMangeEntity fileMangeEntity = fileMangeService.getById(id);
            if (fileMangeEntity != null) {
                if (datasetId == null) {
                    datasetId = fileMangeEntity.getDatasetid();
                }
                if (isParse && "0".equals(fileMangeEntity.getHandle())) {
                    validIds.add(fileMangeEntity.getRagfileid());
                } else if (!isParse && "1".equals(fileMangeEntity.getHandle())) {
                    validIds.add(fileMangeEntity.getRagfileid());
                }
            }
        }

        // 步骤 3: 检查是否有有效操作
        if (!validIds.isEmpty() && datasetId != null) {
            DocumentIdsReq documentIdsReq = new DocumentIdsReq();
            documentIdsReq.setDocument_ids(validIds);

            // 步骤 4: 根据操作类型执行相应操作
            if (isParse) {
                RagFlowApiResult ragFlowApiResult = ragFlowFileService.parseDocuments(datasetId, documentIdsReq);
                if (ragFlowApiResult.getCode() == 0) {
                    for (String id : idList) {
                        FileMangeEntity fileMangeEntity = fileMangeService.getById(id);
                        if (fileMangeEntity != null && "0".equals(fileMangeEntity.getHandle())) {
                            //设置为解析中，进入界面后会调用rag接口返回进度
                            fileMangeEntity.setHandle("1");
                            fileMangeService.updateById(fileMangeEntity);
                        }
                    }
                } else {
                    throw new Exception(ragFlowApiResult.getMessage());
                }
            } else {
                RagFlowApiResult ragFlowApiResult = ragFlowFileService.stopParsingDocuments(datasetId, documentIdsReq);
                for (String id : idList) {
                    FileMangeEntity fileMangeEntity = fileMangeService.getById(id);
                    if (fileMangeEntity != null && "1".equals(fileMangeEntity.getHandle())) {
                        fileMangeEntity.setHandle("0");
                        fileMangeService.updateById(fileMangeEntity);
                    } else {
                        throw new Exception(ragFlowApiResult.getMessage());
                    }
                }
            }
        }
    }

}
